// haoduogeni/createPlan/index.js
var t = getApp();
const api = require('../common/utils/request.js')
const {
  imgJindu,
  addTaskList
} = require('../common/api/user');
const {
  createTask
} = require('../common/api/send')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectShow: false,
    content: '',
    fileList: [],
    imgList: [],
    typeList: [{
        title: '立即发布',
        value: 1
      },
      {
        title: '定时发布',
        value: 2
      },
      {
        title: '循环发布',
        value: 3
      }
    ],
    currentType: 0,
    list: [{
      title: "",
      imgs: [],
      publishType: "1", //1立即发布 2定时发布
      publishDate: "", //定时发布日期
      publishTime: "", //定时发布时间
      uploadType: "1", //1图片 2视频
      time: "", //循环发布时间
      num: "", //循环发布次数
      editorRef: null, //编辑器实例
      release_promotion: "0", //0正常发布 1二维码发布
      release_promotion_type: "1", //1图片 2链接
      selectedKey: null,
      selectedKeyImg: null,
      publishLoop: "1", //定时发布是否循环 0是 1否\
      imgsPoster: [], //海报
    }],
    uploadUrl: "upload.uploadPic",
    datePickerShow: false,
    timeIndex: 0,
    showError: false,
    titleIndex: 0,
    uid: '',
    code: '',
    timerCheckCode: null,
    isLoadding: false,
    setTitleShow: false,//任务名称弹窗
    taskName: '',//任务名称
    user_str: [],//选中的账号id
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.obj){
      this.setData({
        list: JSON.parse(options.obj),
        uid: options.uid
      })
    }else {
      this.setData({
        uid: options.uid,
        // code: options.code ? options.code : ''
      })
    }
    
    // if(this.data.code != ''){
    //   this.getStatusByCode()
    // }
  },
  preViewImg(e){
    console.log(e,'eeeeeeee')
    var index = e.currentTarget.dataset.index;
    var indexs = e.currentTarget.dataset.indexs;
    var imgs = e.currentTarget.dataset.item;
    console.log(index,indexs,imgs,'preViewImg')
    var arr = [];
    imgs.map(item=>{arr.push(item.url)})
    wx.previewImage({
      current: indexs,
      urls: arr
    });
  },
  delTiao(e){
    console.log(e,'走了么')
    var index = e.currentTarget.dataset.index;
    this.data.list.splice(index, 1);
    this.setData({
      list: this.data.list
    })
  },
  delImg(e){
    var index = e.currentTarget.dataset.index;
    var indexs = e.currentTarget.dataset.indexs;
    this.data.list[index].imgs.splice(indexs, 1);
    this.setData({
      list: this.data.list
    })
  },
  createPlan(params) {
    wx.showLoading({
      title: '创建中',
    })
    this.setData({
      isLoadding: true
    })
    var _this = this;
    api.post(createTask, params).then(res => {
      //成功时回调函数
      if (res.errno == 0) {
        
        this.saveCircle(res.data);
       
      } else {
        wx.hideLoading();
        this.setData({
          isLoadding: false
        })
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }).catch(err => {
      //失败时回调函数
      wx.hideLoading();
        this.setData({
          isLoadding: false
        })
    })

  },
  saveCircle(id){
    var _this = this;
    api.post(addTaskList, {
      renwu_id: id,
      pt_id: t.globalData.ptId,
      uid: wx.getStorageSync('yz_uid'),
    }).then(res => {
      //成功时回调函数
      console.log(res, 'getWxUser')
      if (res.errno == 0) {
        wx.hideLoading();
        this.setData({
          isLoadding: false
        })
        wx.showToast({
          title: '创建成功',
          icon: 'none',
          duration: 1000
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/haoduogeni/planList/index',
          })
        }, 1000)
      } else {
        wx.hideLoading();
        this.setData({
          isLoadding: false
        })
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }).catch(err => {
      //失败时回调函数
      console.log(err)
      wx.hideLoading();
        this.setData({
          isLoadding: false
        })
    })
    
  },
  // getStatusByCode(){
  //   wx.showLoading({
  //     title: '生成中',
  //   })
  //   var _this = this;
  //     api.post(imgJindu, {
  //       code: this.data.code,
  //       pt_id: t.globalData.ptId,
  //       uid: wx.getStorageSync('yz_uid'),
  //     }).then(res => {
  //       //成功时回调函数
  //       console.log(res, '检测状态')
  //       if (res.errno == 0) {
  //         // _this.bindUserByuid(res.data);
  //         console.log(res.data,'res.data')
  //         var data = res.data;
  //         const allStatusValid = data.every(item => item.status === 1);
  //         if(allStatusValid){
  //           console.log('停止检测状态')
  //           wx.hideLoading()
  //           var arr1 = []
  //           data.forEach(item => {
  //             arr1.push({
  //               title: item.text,
  //               imgs: item.img,
  //               publishType: "1", //1立即发布 2定时发布
  //               publishDate: "", //定时发布日期
  //               publishTime: "", //定时发布时间
  //               uploadType: "1", //1图片 2视频
  //               time: "", //循环发布时间
  //               num: "", //循环发布次数
  //               editorRef: null, //编辑器实例
  //               release_promotion: "0", //0正常发布 1二维码发布
  //               release_promotion_type: "1", //1图片 2链接
  //               selectedKey: null,
  //               selectedKeyImg: null,
  //               publishLoop: "1", //定时发布是否循环 0是 1否\
  //               imgsPoster: [], //海报
  //             })
  //           })
  //         }else {
  //           _this.data.timerCheckCode = setTimeout(() => {
  //             _this.getStatusByCode();
  //           }, 1000);
  //         }
  //       }else {
  //         wx.hideLoading()
  //       }
  //     }).catch(err => {
  //       //失败时回调函数
  //       console.log(err)
  //       wx.hideLoading()
  //     })
  // },
  onChange(e) {
    this.data.list[this.data.titleIndex].publishLoop = e.detail;
    if(e.detail == 1){
      this.data.list[this.data.titleIndex].num = '';
      this.data.list[this.data.titleIndex].time = ''
    }
    
    this.setData({
      list: this.data.list
    })
  },
  addOne() {
    var list = this.data.list;
    list.push({
      title: "",
      imgs: [],
      publishType: "1", //1立即发布 2定时发布 3循环发布、定时循环发布
      publishDate: "", //定时发布日期
      publishTime: "", //定时发布时间
      uploadType: "1", //1图片 2视频
      time: "", //循环发布时间
      num: "", //循环发布次数
      editorRef: null, //编辑器实例
      release_promotion: "0", //0正常发布 1二维码发布
      release_promotion_type: "1", //1图片 2链接
      selectedKey: null,
      selectedKeyImg: null,
      publishLoop: "1", //定时发布是否循环 0是 1否\
      imgsPoster: [], //海报
    })
    this.setData({
      list: list
    })
  },
  

  afterRead: function (e) {
    var i = this,
      n = e.detail.file,
      s = a.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: s,
      filePath: n.url,
      name: "file",
      formData: null,
      success: function (a) {
        var e = JSON.parse(a.data),
          s = i.data.fileList,
          o = void 0 === s ? [] : s;
        o.push(t(t({}, n), {}, {
          url: e.data.img_url
        })), i.data.imgList.push(e.data.img_url), i.setData({
          fileList: o
        });
      }
    });
  },
  changeCon(e) {
    var text = e.detail.value;
    this.data.list[this.data.titleIndex].title = text;
    this.setData({
      list: this.data.list
    })
  },
  changeNum(e) {
    this.data.list[this.data.titleIndex].num = e.detail.value;
    this.setData({
      list: this.data.list
    })
  },
  changeTime(e) {
    this.data.list[this.data.titleIndex].time = e.detail.value;
    this.setData({
      list: this.data.list
    })
  },
  datePickerConfirm(e) {
    console.log(e,'eeeeeeeeeeeeeeeeeee',this.data.timeIndex)
    var index = this.data.timeIndex;
    var time = e.detail.time;
    this.data.list[index].publishTime = time;
    this.setData({
      list: this.data.list
    })
  },
  datePickerCancel() {},
  selectTime(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      datePickerShow: true,
      timeIndex: index
    })
  },
  changeType(e) {
    var index = e.currentTarget.dataset.index;
    var indexs = e.currentTarget.dataset.indexs;
    this.data.list[index].publishType = indexs + 1;
      this.data.list[index].publishTime = '';
      this.data.list[index].num = '';
      this.data.list[index].time = '';
      this.data.list[index].publishLoop = '1';
    this.setData({
      list: this.data.list
    })
  },
  onRead: function (e) {
    var index = e.currentTarget.dataset.index;
    var _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success: function (a) {
        var o = a.tempFilePaths;
        var s = o[0];
        wx.showLoading({
          title: '上传中',
        })
        wx.uploadFile({
          url: api.uploadFileUrl,
          filePath: s,
          name: "file",
          success: function (a) {
            var e = JSON.parse(a.data);
            wx.hideLoading();
            if (e.errno == 0) {
              _this.data.list[index].imgs.push(e.data);
              _this.setData({
                list: _this.data.list
              })
            } else {
              wx.showToast({
                icon: "none",
                title: e.msg,
                duration: 1500
              });
            }
            // 1 == e.result ? t.setData({
            //     imageUrl: e.data.img_url,
            //     "applyModel.storeImg": e.data.img_url
            // }) : 
          },
          fail: function (a) {
            wx.hideLoading();
          }
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  titleClick(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      titleIndex: index
    })
  },
  create() {
    for (let i = 0; i < this.data.list.length; i++) {
      const item = this.data.list[i];

      // 检查 title 是否为空
      if (item.title === '') {
        this.data.showError = true;
        wx.showToast({
          title: '标题不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }

      // 检查 imgs 是否为空
      if (item.imgs.length === 0 && item.release_promotion == "0") {
        this.data.showError = true;
        wx.showToast({
          title: '素材不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if (item.imgsPoster.length === 0 && item.release_promotion == "2") {
        this.data.showError = true;
        wx.showToast({
          title: '海报不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if(item.release_promotion == "1" && item.release_promotion_type == 1  && item.selectedKeyImg == null){
        this.data.showError = true;
        wx.showToast({
          title: '图片分类不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if(item.release_promotion == "1" && item.release_promotion_type == 2 && item.selectedKey == null){
        this.data.showError = true;
        wx.showToast({
          title: '链接分类不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }

      // 检查 publishType 为 2 时 publishDate 是否为空
      if (item.publishType == 2 && item.publishTime == "") {
        this.data.showError = true;
        wx.showToast({
          title: '发布时间不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if ((item.publishType == "2" && item.publishLoop == "0") && item.time == "") {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布间隔时间不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if ((item.publishType == "2" && item.publishLoop == "0") && item.num == "") {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布次数不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if ((item.publishType == "2" && item.publishLoop == "0") && item.time < 1) {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布间隔时间不能少于1分钟',
          icon: 'none'
        })
        return; // 退出函数
      }
      if ((item.publishType == "2" && item.publishLoop == "0") && item.time > 719) {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布间隔时间不能大于12小时',
          icon: 'none'
        })
        return; // 退出函数
      }
      
      if ((item.publishType == "2" && item.publishLoop == "0") && item.num < 1) {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布次数不能少于1次',
          icon: 'none'
        })
        return; // 退出函数
      }
      if (item.publishType == "3" && item.time == "") {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布时间不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if (item.publishType == "3" && item.num == "") {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布次数不能为空',
          icon: 'none'
        })
        return; // 退出函数
      }
      if (item.publishType == "3" && item.time < 1) {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布间隔时间不能少于1分钟',
          icon: 'none'
        })
        return; // 退出函数
      }
      if (item.publishType == "3" && item.time >719) {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布间隔时间不能大于12小时',
          icon: 'none'
        })
        return; // 退出函数
      }
      if (item.publishType == "3" && item.num < 1) {
        this.data.showError = true;
        wx.showToast({
          title: '循环发布次数不能少于1次',
          icon: 'none'
        })
        return; // 退出函数
      }
    }
    
    this.data.showError = false;
    if(!this.data.showError){
      this.setData({
        selectShow: true
      })
    }
    this.setData({
      selectShow: true
    })

  },
  setTitleConfirm(data){
    this.setData({
      taskName: data.detail
    })
    this.toCreateFormat()
  },
  selectOk(data) {
    this.setData({
      user_str: data.detail,
      setTitleShow: true
    })
  },
  toCreateFormat() {
    var arr1 = [];
    this.data.list.forEach(item => {
      const arr2 = [];
      // item.imgs.forEach((items) => {
      //   arr2.push(items.response.data.id);
      // });
      item.imgs.forEach((items) => {
        arr2.push(items.id);
      });
      arr1.push({
        title: item.title.replace(/\n/g, '|'),
        imgs: item.release_promotion == 0 ? arr2 : item.release_promotion == 2 ? arr3 : [],
        // release_type: item.publishType,
        release_type: (item.publishType == 2 && item.publishLoop == 0) ? 3 : item.publishType, //图片
        release_time: item.publishType == 2 ?
          item.publishDate.format("YYYY-MM-DD HH:mm") :
          "",
        release: 1, //图片
        num: item.publishType == 3 ? item.num : (item.publishType == 2 && item.publishLoop == 0 ? item.num : ""), //循环次数
        time: item.publishType == 3 ? item.time : (item.publishType == 2 && item.publishLoop == 0 ? item.time : ""), //循环时间
        promotion: item.release_promotion, //推广类型
        promotion_type: item.release_promotion == 1 ? item.release_promotion_type : '',
        // promotion_ids: item.selectedKey ? item.selectedKey.toString() : '', //推广链接ID
        promotion_ids: item.release_promotion == 1 ? (item.release_promotion_type == 2 ? (item.selectedKey ? item.selectedKey.toString() : '') : (item.selectedKeyImg ? item.selectedKeyImg.toString() : '')) : '', //推广链接ID
      })
    })
    var obj = {
      content: JSON.stringify(arr1),
      name: this.data.taskName,
      position: "",
      uid: this.data.uid,
      user_str: JSON.stringify(this.data.user_str),
      user_type: 1
    }
    this.createPlan(obj);
    // wx.navigateTo({
    //   url: '/haoduogeni/createPlaning/index?obj=' + JSON.stringify(obj),
    // })
  },
  getCurrentFormattedTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
    var day = String(date.getDate()).padStart(2, '0');
    var hours = String(date.getHours()).padStart(2, '0');
    var minutes = String(date.getMinutes()).padStart(2, '0');
    var seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}${month}${day}${hours}${minutes}${seconds}`;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})